package com.laoye.big_event.Controller;
import com.laoye.big_event.Pojo.Result;
import com.laoye.big_event.Pojo.User;
import com.laoye.big_event.Service.UserService;
import com.laoye.big_event.Utils.JwtUtil;
import com.laoye.big_event.Utils.Md5Util;
import com.laoye.big_event.Utils.ThreadLocalUtil;
import jakarta.validation.constraints.Pattern;
import org.hibernate.validator.constraints.URL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;


import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
@Validated
public class UserController {
    @Autowired
    UserService userService;
    //注册  请求参数格式：x-www-form-urlencoded
    @PostMapping("/register")
    public Result Register(@Pattern(regexp = "^\\S{5,16}$") @RequestParam("username") String username,
                           @Pattern(regexp = "^\\S{5,16}$") @RequestParam("password") String password) {
        //查询用户
        User user=userService.SelectByUsername(username);
        //用户名没有被占用
        if(user==null){
            //注册
            userService.RegisterUser(username,password);
            return Result.success();
        }else{
            //用户名被占用
            return Result.error("用户已经存在");

        }
    }

    @Autowired
    private StringRedisTemplate redis;
//    登录  请求参数格式：x-www-form-urlencoded
    @PostMapping("/login")
    public Result Login(@Pattern(regexp = "^\\S{5,16}$") String username,
                        @Pattern(regexp = "^\\S{5,16}$") String password) {
        User user = userService.SelectByUsername(username);
        if(user==null){
            return Result.error("用户不存在");
        }
//        验证密码是否正确，密文验证
        if(Md5Util.checkPassword(password,user.getPassword())){
            Map<String,Object> claims=new HashMap<>();
            claims.put("id",user.getId());
            claims.put("username",user.getUsername());
            //登陆成功获取令牌
            String Token= JwtUtil.genToken(claims);
//            把令牌存储到redis中
            redis.opsForValue().set(Token,Token,12, TimeUnit.HOURS);
            return Result.success(Token);
        }
        return Result.error("密码错误");
    }
//    获取用户基本信息
    @GetMapping("/userinfo")
    public Result Userinfo(/*@RequestHeader(name ="Authorization")String token*/) {
        /*Map<String, Object> map = JwtUtil.parseToken(token);
        String username = (String) map.get("username");*/

        //从ThreadLocal获取拦截器中存储的数据
        Map<String, Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        User user = userService.SelectByUsername(username);
        return Result.success(user);
    }
//    更新用户基本信息  请求参数格式：application/json
    @PutMapping("/update")
//    @Validated用在这是因为在user的bean中对参数进行了校验
    public Result Update(@RequestBody @Validated User user) {
        userService.update(user);
        return Result.success();
    }

//    更新头像  请求参数格式：queryString
    @PatchMapping("updateAvatar")
    public Result UpdateAvatar(@RequestParam() @URL String avatarUrl) {
        userService.updateAvatar(avatarUrl);
        return Result.success();
    }

//    更改密码    请求参数格式：application/json
    @PatchMapping("updatePwd")
    public Result updatePwd(@RequestBody Map<String,String> params,@RequestHeader("Authorization") String token) {
        String oldPwd = params.get("old_pwd");
        String newPwd = params.get("new_pwd");
        String rePwd = params.get("re_pwd");
        if(!(newPwd.matches("^\\S{5,16}$")&&rePwd.matches("^\\S{5,16}$"))){
            return Result.error("新密码应为5~16位非空字符");
        }
//        校验密码非空
        if(!StringUtils.hasLength(oldPwd) || !StringUtils.hasLength(newPwd) || !StringUtils.hasLength(rePwd)){
            return Result.error("缺少必要的参数");
        }
//        校验原密码是否正确
        Map<String,Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        int id = (int) map.get("id");
        User user = userService.SelectByUsername(username);
        String password = user.getPassword();
        if (!Md5Util.checkPassword(oldPwd,password)) {
            return Result.error("原密码填写不正确");
        }
//        检验两次新密码填写是否一致
        if(!newPwd.equals(rePwd)){
            return Result.error("两次密码填写不一致");
        }
//        校验完毕，更新密码
        userService.updatePwd(newPwd,id);
//        删除redis中的token
        redis.opsForValue().getOperations().delete(token);
        return Result.success();
    }
}
